LeetCode Js-231. Power of Two
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
給予一個整數 n,如果此值是二的次方,回傳 true,否則回傳 false。
如果這裡存在一個整數 x 為 n 等於 2^x,則 n 是 2 的次方。
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Solution:
Code:
var isPowerOfTwo = function(n) {
if (n <= 0) return false
if (n === 1) return true
while (n > 5) {
n = n / 2
}
return n % 2 === 0
};
FlowChart:
Example 1
Input: n = 1
if (n === 1) return true